package com.kaifamiao.repository.impl;

import com.kaifamiao.entity.User;
import com.kaifamiao.handler.UserListResultSetHandler;
import com.kaifamiao.handler.UserResultSetHandler;
import com.kaifamiao.repository.UserRepository;
import com.kaifamiao.utils.DataSourceUtil;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import javax.sql.DataSource;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * @author lucien-ma
 * @date 2021/10/12
 * @apiNote
 */
public class UserRepositoryImpl implements UserRepository {

    private static String url = "jdbc:mysql://localhost:3306/demo01?useUnicode=true&characterEncoding=UTF-8";
    private static String username = "root";
    private static String password = "root";
    private QueryRunner queryRunner = new QueryRunner(
            DataSourceUtil.getDataSource(url,username,password));

    @Override
    public List<User> findAll() {
        try {
            return queryRunner.query(
                    "select * from users",
                    new UserListResultSetHandler()
            );
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public User findById(Integer id) {
        try {
            return queryRunner.query(
                    "select * from users where id = ?",
                    new UserResultSetHandler(),
                    id
            );
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public int save(User user) {
        try {
            return queryRunner.update(
                    "insert into users(id, username, password) values(?,?,?)",
                    user.getId(),user.getUsername(),user.getPassword()
            );
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return -1;
    }

    @Override
    public int update(User user) {
        try {
            return queryRunner.update(
                    "update users set username=?,password=? where id=?",
                    user.getUsername(), user.getPassword(), user.getId()
            );
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return -1;
    }

    @Override
    public int deleteById(Integer id) {
        try {
            return queryRunner.update(
                    "delete from users where id=?",
                    id
            );
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return -1;
    }
}
